package org.tinygame.herostory;

import com.google.protobuf.GeneratedMessageV3;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.AttributeKey;
import org.tinygame.herostory.model.UserManager;
import org.tinygame.herostory.msg.GameMsgProtocol;



public class GameMsgHandler extends SimpleChannelInboundHandler {



    /**
     * 通道激活时触发该方法，相当于用户上线时初次与服务器成功建立连接后触发该方法
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        //用户信道激活时，加入到组中，后期用于广播消息
        Broadcaster.addChannel(ctx.channel());
    }

    /**
     * 客户端连接断开的时候触发
     * @param ctx
     * @throws Exception
     */
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        super.handlerRemoved(ctx);
        //将客户端连接从组中移除
        Broadcaster.removeChannel(ctx.channel());

        //从channel中获取用户ID，这个ID是用户上线的时候加到channel中的
        Integer userId = (Integer) ctx.channel().attr(AttributeKey.valueOf("userId")).get();

        if (null == userId){
            return;
        }
        //从通道组中删除这个用户
        UserManager.removeUserById(userId);

        //构建该用户下线的消息
        GameMsgProtocol.UserQuitResult.Builder resultBuilder = GameMsgProtocol.UserQuitResult.newBuilder();
        resultBuilder.setQuitUserId(userId);
        GameMsgProtocol.UserQuitResult newResult = resultBuilder.build();
        //群发给组中的所有连接
        Broadcaster.broadcast(newResult);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("收到客户端消息,msgClazz = "+msg.getClass().getName()+",msg = " + msg);
        if (msg instanceof GeneratedMessageV3) {
            MainThreadProcessor.getInstance().process(ctx,(GeneratedMessageV3) msg);
        }
    }






}
